package com.learn.ProducerConsumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * lock 生产者消费者
 * 使用Lock（lock + unlock） + Condition（await + signalAll）
 */
public class LockPc {

    public static void main(String[] args) {
        Way2 way = new Way2();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> way.incr()).start();
            new Thread(() -> way.decr()).start();
        }
    }
}


class Way2{
    public int num = 1;
    Lock lock = new ReentrantLock();
    Condition con = lock.newCondition();

    //卖票
    public void incr(){
        lock.lock();
        try{
            while(num==0){
                con.await();
            }
            num--;
            System.out.println(Thread.currentThread().getName()+"=>"+num);
            con.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }



    public void decr(){
        lock.lock();
        try {
            while(num>0){
                con.await();
            }
            num++;
            System.out.println(Thread.currentThread().getName()+"=>"+num);
            con.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}